package src.com.java.dtgh.threeDay;

import src.com.java.Util;

public class demo3 {

    public static void main(String[] args) {

        int[] arr = {1,1,1,1,1};
        demo3 demo3 = new demo3();
        demo3.findTargetSumWays(arr,3);
    }

    public int findTargetSumWays(int[] nums, int target) {

        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        /**
         *   left + right = sum
         *   left - right = target
         *   left = (sum + target) / 2
         */
        if((sum + target) % 2 != 0){
            return 0;
        }
        if(target > sum) return 0;

        int left = (sum + target) >> 1;

        int len = nums.length;

        int[][] dp = new int[len + 1][left + 1];

        dp[0][0] = 1;

        for(int i = 1;i <= len;i++){
            for(int j = 0;j <= left;j++){
                dp[i][j] = dp[i-1][j];
                if(j >= nums[i - 1]){
                    dp[i][j] += dp[i-1][j - nums[i - 1]];
                }
            }
        }

        return dp[len][left];



    }

    public int findTargetSumWays2(int[] nums, int target) {

        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        /**
         * left + right = sum
         * left - right = target
         * right * 2 = sum - target
         * right = (sum - target) / 2;
         */
        int diff = sum - target;
        if(diff < 0 || diff % 2 != 0){
            return 0;
        }
        int neg = diff >> 1;
        int len = nums.length;
        int[][] dp = new int[len + 1][neg + 1];
        dp[0][0] = 1;
        for(int i = 1;i <= len;i++){
            for(int j = 0;j <= neg;j++){
                dp[i][j] = dp[i-1][j];
                if(j >= nums[i - 1]){
                    dp[i][j] += dp[i-1][j - nums[i - 1]];
                }
            }
        }
        return dp[len][neg];
    }
}
